package cn.edu.sziit.bbs.controller;

import cn.edu.sziit.bbs.model.User;
import cn.edu.sziit.bbs.service.UserService;
import cn.edu.sziit.bbs.util.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//register.jsp
@Controller
public class RegisterController {
    @Autowired
    UserService userService;

    /**
     * 跳转到register.jsp注册页面
     *
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String showRegister() {

        return "register";
    }

    /**
     * 验证码
     *
     * @param request
     * @param response
     * @param session
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException {
        CaptchaUtil.outputCaptcha(request, response);
        System.out.println(session.getAttribute("randomString"));
    }

    /**
     * 注册验证和插入
     *
     * @param user
     * @param userPassword2
     * @param code
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public Map<String, String> registerInsert(User user, String userPassword2, String code,
                                              HttpSession session) {
        Map<String, String> map = new HashMap<>();

        String info = userService.checkRegister(user, userPassword2, code, session);

        if (info.equals("注册成功")) {
            userService.insert(user);
        }

        map.put("info", info);
        return map;
    }

}
